package com.gougou.search.mq.handler;

import com.gougou.search.entity.Item;
import com.gougou.search.service.ItemSearchService;
import com.gougou.search.service.ItemService;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.client.solrj.impl.XMLResponseParser;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

@Component
public class ItemMQHandler {

    private static final ObjectMapper MAPPER = new ObjectMapper();
    // solr数据交互地址
    private static final String URL = "http://132.232.50.106:8983/gougou";

    @Autowired
    private ItemService itemService;

    private ItemSearchService itemSearchService;

    // 初始化ItemSearchService
    ItemMQHandler(){
        HttpSolrServer httpSolrServer = new HttpSolrServer(URL);
        httpSolrServer.setParser(new XMLResponseParser()); // 设置响应解析器
        httpSolrServer.setMaxRetries(1); // 设置重试次数，推荐设置为1
        httpSolrServer.setConnectionTimeout(1000); // 建立连接的最长时间
        this.itemSearchService = new ItemSearchService(httpSolrServer);
    }

    /**
     * 处理消息，新增、修改、删除的消息，将商品数据同步到solr中
     * 消息中并没有包含商品的基本数据，需要通过id到后台系统提供的接口中获取
     * 
     * @param msg
     */
    @RabbitListener(queues = "GOUGOU-SEARCH-ITEM-QUEUE")
    public void execute(String msg) {
        try {
            JsonNode jsonNode = MAPPER.readTree(msg);
            Long itemId = jsonNode.get("itemId").asLong();
            String type = jsonNode.get("type").asText();
            if (StringUtils.equals(type, "insert") || StringUtils.equals(type, "update")) {
                Item item = this.itemService.queryById(itemId);
                itemSearchService.add(item);
            } else if (StringUtils.equals(type, "delete")) {
                itemSearchService.delete(itemId.toString());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
